package com.itshizhan.itjidancideveloper.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import org.aspectj.apache.bcel.classfile.Code;

import java.io.Serializable;
import java.util.Calendar;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class Response<T> implements Serializable {
	private Integer code;
	private String msg;
	private T data;
	private Long timestamp;


	public Response(Integer code, String msg) {
		this.code = code;
		this.msg = msg;
		this.timestamp = timestamp();
	}

	public Response(Integer code, String msg, T data) {
		this.code = code;
		this.msg = msg;
		this.data = data;
		this.timestamp = timestamp();
	}


	private Long timestamp() {
		return Calendar.getInstance().getTimeInMillis();
	}

	// 成功，不需要返回数据
	public static <T> Response<T> success(){
		return new Response<T>(CodeMsgEnum.SUCCESS.getCode(),CodeMsgEnum.SUCCESS.getMsg());
	}

	// 成功，返回数据
	public static <T> Response<T> success(T data){
		return new Response<T>(CodeMsgEnum.SUCCESS.getCode(), CodeMsgEnum.SUCCESS.getMsg(), data);
	}


	//错误，不需要告知原因 和 错误码
	public static <T> Response<T> fail(){
		return new Response<T>(CodeMsgEnum.Fail.getCode(), CodeMsgEnum.Fail.getMsg());
	}
	//错误，告知原因
	public static <T> Response<T> fail(String msg) {
		return new Response<T>(CodeMsgEnum.Fail.getCode(), msg);
	}
	//错误，告知原因 和 错误码
	public static <T> Response<T>  fail(CodeMsgEnum codeMsgEnum){
		return new Response<T>(codeMsgEnum.getCode(), codeMsgEnum.getMsg());
	}


	@Override
	public String toString() {
		return "Response{" +
				"code=" + code +
				", msg='" + msg + '\'' +
				", data=" + data +
				", timestamp=" + timestamp +
				'}';
	}

	public static void main(String[] args) {
		System.out.println(Response.success());
		System.out.println(Response.success("[1,2,3]"));
		System.out.println(Response.fail());
		System.out.println(Response.fail("服务异常"));
		System.out.println(Response.fail(CodeMsgEnum.UNKNOWN_ERROR));
	}
}
